package com.group.yqxxb.response;

import com.alibaba.fastjson.JSONObject;
import com.group.yqxxb.Exception.MyException;
import com.group.yqxxb.eums.ResultEnum;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * @author qyyzxty@icloud.com
 * @data 2021/1/27
 * 返回数据
 **/
@Data
public class R<T> {

    //错误码
    private Integer code;

    //提示信息
    private String msg;

    //具体内容
    private T data;

    //私有构造类 构造返回对象
    private R(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    //私有构造类 通过自定义的MyException异常构造返回类
    private R(MyException e) {
        this.code = (e).getCode();
        this.msg = (e).getMsg();
        this.data = null;
    }

    //私有构造类 通过enum枚举类构造返回类
    private R(ResultEnum resultEnum, T data) {
        this.code = resultEnum.getCode();
        this.msg = resultEnum.getMsg();
        this.data = data;
    }

    private R(Exception e){
        this.msg = e.getMessage();
        this.code = 10000;
        this.data = null;
    }

    //通过字符串构造返回类
    public R(String s) {
        this.code = 10000;
        this.msg = s;
        this.data = null;
    }

    //发生异常的时候的通过MyException构造返回类
    public static R error( MyException e ) {
        //如果是我们自己抛出的异常的话就按照异常的消息返回
        return new R( e );
    }

    //发生常见异常时通过enum枚举类构造返回类
    public static R error(ResultEnum resultEnum) { return new R(resultEnum, null); }
    //发生常见异常时通过String构造返回类
    public static R error(String s) {
        return new R(s);
    }

    //成功的返回类
    public static<S> R success(S data) {
        return new R(ResultEnum.SUCCESS, data);  //将成功返回的data数据传进去
    }

    //通过异常枚举类构造map
    public static JSONObject getJsonByEnum(ResultEnum resultEnum) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", resultEnum.getCode());
        jsonObject.put("msg", resultEnum.getMsg());
        return jsonObject;
    }

    public static JSONObject getJsonByEnum(MyException e) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", e.getCode());
        jsonObject.put("msg", e.getMsg());
        return jsonObject;
    }

    public static R error(Exception e){
        return new R(e);
    }

    //失败的返回类，返回码为231
    public static<S> R error(){ return new R(231,"操作失败！",null);}
}